var textdata = {};

(function($){

    $.fn.extend({
        multipageform : function(options, arg) {
            if (typeof(options) == "object") {
                options = $.extend({}, $.multipageform.defaults, options);
            }
            this.each(function() {
/*
                for (var fld in options) {
                    jQuery(this).attr("plugin_mf_" + fld, options[fld]);
                }
*/
                new $.multipageform(this, options, arg);
            });
            return;
        }
    });

    var refreshEmpty = function(item) {
        jQuery(item).find("fieldset").each(function(ndx, fieldsetitem) {
            var empty = true;
            jQuery(fieldsetitem).find("input[type='text']").each(function(ndx2, inputitem) {
                if (jQuery(inputitem).val() != "") { empty = false; }
            });
            if (empty) {
                jQuery("div.mf_header span:nth-child(" + (ndx+1) + ")").addClass("empty");
            } else {
                jQuery("div.mf_header span:nth-child(" + (ndx+1) + ")").removeClass("empty");
            }
        });
    }

    var setLayout = function(item) {
        jQuery("<div>")
            .attr("id", item.name + "_pages")
            .addClass("mf_header")
            .html("&nbsp;")
        .prependTo(jQuery(item).parents().first())
        ;
/*
        jQuery("<div>")
            .attr("id", item.name + "_content")
            .addClass("mf_content")
            .html("&nbsp;")
        .appendTo(jQuery(item).parents().first())
        ;
*/
    }

    var formSectionSelected = function(formItem, item) {
        refreshEmpty(formItem);
        var ndx = parseInt(item.id, 10) + 2 ;
        jQuery(item).parents("").first().children("span").removeClass("selected");
        jQuery(item).addClass("selected");
        jQuery(formItem).find("fieldset").hide("fade", {}, 200);
        jQuery(formItem).find("fieldset:nth-child(" + ndx + ")").show("fade", {}, 200);
    }

    $.multipageform = function(item, options, arg) {
        var myName = item.name;
        var timeout = null;
        var pos = jQuery(item).offset();
        if (typeof(options) == "string") {
            var methodName = options;
            options = {};
/*
            for (var fld in $.multipageform.defaults) {
                options[fld] = jQuery(item).attr("plugin_mf_" + fld);
            }
*/
            // methods
        } else {
            jQuery(item).find("input").change(function() {
                jQuery(this).addClass("changed");
            });
            jQuery(item).find("select").change(function() {
                jQuery(this).addClass("changed");
            });
            jQuery(item).find("fieldset").hide();
            setLayout(item);
            jQuery(item).find("legend").each(function(ndx, legend) {
                jQuery("div#" + item.name + "_pages").append(
                    jQuery("<span>")
                        .attr("id", ndx)
                        .text(jQuery(legend).text())
                        .addClass(ndx == 0 ? "selected" : "")
                        .click(function() {
                            var result = true;
                            if (options.onselect) {
                                result = options.onselect(jQuery("span.selected").attr("id"), ndx);
                            }
                            if (result) {
                                formSectionSelected(item, this);
                            }
                        })
                    )
                ;
            });
            jQuery(item).find("fieldset").first().show();
            refreshEmpty(item);
        }

        $.multipageform.defaults = {
            onselect : null
        }
    }
})(jQuery);

function multiform_changed(mf, tabIndex) {
    var ndx = parseInt(tabIndex, 10) + 2;
    var fs = mf.find("fieldset:nth-child(" + ndx + ") *.changed");
    if (fs.size() > 0) { return true; }
    return false;
}

function multiform_validateTab(mf, tabIndex) {
    var ndx = parseInt(tabIndex, 10) + 2;
    var valid = true;
    var msgArray = {};
    mf.find("fieldset:nth-child(" + ndx + ") *[required='1']").each(function(n, item) {
        if (item.value == "") {
            valid = false;
            msgArray[item.name] = {};
            msgArray[item.name].code = 3;
            msgArray[item.name].msg = "You have to fill the required fields!";
        }
    });
    if (!valid) {
        displayFormErrors(msgArray);
    }
    return valid;
}

function multiform_saveCurrentTab(mf, tabIndex, waitMsg, buttonItem, extraData, callback) {
    jQuery("input.error").removeClass("error");
    var waitMsg = (waitMsg === undefined ? "Submitting form, please wait" : waitMsg);
    var url = jQuery(buttonItem).parents("form").first().attr("action");
    var ndx = parseInt(tabIndex, 10) + 2;
    if (ndx > mf.children("fieldset").size()) {
        ndx = mf.children("fieldset").size()+1;
    }
    var params = {};
    var valid = multiform_validateTab(mf, tabIndex);
    if (!valid) { return; }
    mf.find("fieldset:nth-child(" + ndx + ") input").each(function(n, item) {
        if (item.type == "text" || item.type == "password" || item.type == "hidden") {
            if (jQuery(item).hasClass("impex_choice")) {
                return;
            } else if (jQuery(item).hasClass("hsinput")) {
                params[item.name] = jQuery(item).attr("datavalue");
            } else {
                params[item.name] = item.value;
            }
        } else if (item.type == "radio" || item.type == "checkbox") {
            if (item.checked) { params[item.name] = item.value; }
        }
    });
    mf.find("fieldset:nth-child(" + ndx + ") select").each(function(n, item) {
        params[item.name] = item.value;
    });
    mf.find("fieldset:nth-child(" + ndx + ") textarea").each(function(n, item) {
        params[item.name] = item.value;
    });
    if (extraData) { params.extra = extraData; }
    var tbl = jQuery(buttonItem).parents("table").first();
    jQuery.ajax(url, {
        data : params,
        type : "POST",
        dataType : "json",
        success : function(res) {
            tbl.find("td").last().empty().append(
                jQuery("<div>").text("Form submitted")
            );
            setTimeout(function() {
                tbl.find("td").last().find("div").hide("fade", {}, 300);
            }, 3000);
            if (res.type == "validation") {
                if (!res.overall) {
                    displayFormErrors(res.msgArray);
                }
            }
            if (res.success) {
                jQuery("div.form_errors").hide("fade", {}, 300);
                if (callback) { callback(); }
                if (res.redirect) {
                    window.location= generateRequestedUrl(res.redirect);
                }
            }
        }
    });
}

function multiform_switch(mf, switchTo) {
    mf.find("fieldset").each(function(ndx, fieldsetitem) {
        var empty = true;
        jQuery(fieldsetitem).find("input[type='text']").each(function(ndx2, inputitem) {
            if (jQuery(inputitem).val() != "") { empty = false; }
        });
        if (empty) {
            jQuery("div.mf_header span:nth-child(" + (ndx+1) + ")").addClass("empty");
        } else {
            jQuery("div.mf_header span:nth-child(" + (ndx+1) + ")").removeClass("empty");
        }
    });
    jQuery("span[id='" + switchTo + "']").parents("").first().children("span").removeClass("selected");
    jQuery("span[id='" + switchTo + "']").addClass("selected");
    mf.find("fieldset").hide("fade", {}, 200);
    mf.find("fieldset:nth-child(" + (switchTo+2) + ")").show("fade", {}, 200);
}
